package com.fch.loadlib;

import android.util.Log;

import org.apache.commons.net.ftp.FTP;
import org.apache.commons.net.ftp.FTPClient;

import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;

public class FTPDownloader {
    public static void downloadFile(String server, int port, String user, String password, String remoteFilePath, String localPath) throws IOException {
        FTPClient ftpClient = new FTPClient();
        try {
            ftpClient.connect(server, port);
            ftpClient.login(user, password);
            ftpClient.enterLocalPassiveMode();
            ftpClient.setFileType(FTP.BINARY_FILE_TYPE);
            String remoteFileName = remoteFilePath.substring(remoteFilePath.lastIndexOf('/') + 1);
            String localFilePath = localPath + "/" + remoteFileName;
            FileOutputStream outputStream = new FileOutputStream(localFilePath);
            InputStream inputStream = ftpClient.retrieveFileStream(remoteFilePath);
            byte[] bytesArray = new byte[4096];
            int bytesRead = -1;
            while ((bytesRead = inputStream.read(bytesArray)) != -1) {
                outputStream.write(bytesArray, 0, bytesRead);
            }
            boolean success = ftpClient.completePendingCommand();
            if (success) {
                System.out.println("File has been downloaded successfully.");
            }
            outputStream.close();
            inputStream.close();
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            try {
                ftpClient.disconnect();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }

    public static void DownLoadTest() {
        String server = "//192.168.21.200";
        int port = 21;
        String user = "Program";
        String password = "Program";
        String remoteFile = "/UnityAssets/CreatParty/Temp/image.jpg";
        String localFile = "F://_Test/image.jpg";

        FTPClient ftpClient = new FTPClient();
        try {
            // 连接到 FTP 服务器
            ftpClient.connect(server, port);
            ftpClient.login(user, password);
            ftpClient.enterLocalPassiveMode();

            Log.e("DownLoadTest!","连接到了服务器！");

            // 下载文件
            FileOutputStream outputStream = new FileOutputStream(localFile);
            ftpClient.retrieveFile(remoteFile, outputStream);
            outputStream.close();

            // 关闭 FTP 连接
            ftpClient.logout();
            ftpClient.disconnect();
        } catch (IOException ex) {
            System.err.println("Error occurred: " + ex.getMessage());
            ex.printStackTrace();
        }
    }

}
